package com.ys.controller.api.account;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bo.dto.NameValueDto;
import com.ys.entity.finance.TcwPaymentApply;
import com.ys.service.sys.PdfService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.account.TcwAdvanceAccountRecharge;
import com.ys.entity.sys.YsCol;
import com.ys.service.account.TcwAdvanceAccountRechargeService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 *预支账户充值单
 */
@Controller
@RequestMapping("/api/inter/tcwAdvanceAccountRecharge")
public class ApiInterTcwAdvanceAccountRechargeController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwAdvanceAccountRechargeController.class);


    @Autowired
    private CommonApiService<TcwAdvanceAccountRecharge> commonApiService;
    @Autowired
    private TcwAdvanceAccountRechargeService tcwAdvanceAccountRechargeService;

    @Autowired
    private YspTaskService yspTaskService;

    private final String PERMISSIONS_ADD = "tcwAdvanceAccountRecharge:add";

    @Autowired
    private PdfService pdfService;
    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwAdvanceAccountRecharge setSeachSql(TcwAdvanceAccountRecharge cond){

        cond.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
            .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS auditingTime");//审核时间

        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
            .addField("U.UserId + '/' + U.UserName AS createUserName");//制单人

        cond.addLeftJoin("THR_OperateCompanyApply C ON C.Vgsbm = A.Vgsbm ")
                .addField("C.Vgsjc AS vgsjc");//运营公司简称

        cond.addLeftJoin("TB_CompanyInfo CI ON CI.Vid = A.CompanyVid ")
                .addField("CI.Vname AS vname");//所属公司

        cond.addLeftJoin("TB_CompanyBankInfo CB ON CB.Id = A.CompanyBankInfoId ")
                .addField("CB.Vyhzhmc AS vyhzhmc")//付款账户名称
                .addField("CB.Vyhzh AS vyhzh")//付款账号
                .addField("CB.Vkhh AS vkhh");//付款开户行

        cond.addLeftJoin("TCW_AdvanceAccount AA ON AA.Id = A.AdvanceAccountId ")
                .addField("AA.Code AS code")//预支账户编码
                .addField("AA.Name AS name");//付款账户名称


        //cond.addLeftJoin("TS_UserBankInfo UB ON AA.UserBankInfoId = UB.Id")
        cond.addLeftJoin("TS_UserInfo B on  B.UserId = AA.UserId")
            .addLeftJoin("TS_OrganizationInfo O on  O.Orgid = AA.Orgid")
                .addField("O.DeptName AS deptName")//账户管理部门
                .addField("B.RoleName AS roleName")//负责人岗位
                .addField("(B.UserId + '/' + B.UserName) AS nameLinked")//账户管理负责人

            .addLeftJoin("TS_UserBankInfo UB ON AA.UserBankInfoId = UB.Id AND AA.AccountType=0")
                .addLeftJoin("TCW_PartnerBankInfo PB ON AA.PartnerBankInfoId = PB.Id AND AA.AccountType=1")
                //.addField("CASE WHEN AA.AccountType=0 THEN U.Vyhzhmc ELSE P.Vyhzhmc END _ys_vyhzhmc")//银行账户名称
                //.addField("CASE WHEN AA.AccountType=0 THEN U.Vkhh ELSE P.Vkhh END _ys_vkhh")//开户行
                //.addField("CASE WHEN AA.AccountType=0 THEN U.Vyhzh ELSE P.Vyhzh END _ys_vyhzh")//银行账户编码

                .addField("CASE WHEN AA.AccountType=0 THEN UB.Vyhzhmc ELSE PB.Vyhzhmc END vyhzhmcByAdvance")//银行账户名称
                .addField("CASE WHEN AA.AccountType=0 THEN UB.Vkhh ELSE PB.Vkhh END vkhhByAdvance")//开户行
                .addField("CASE WHEN AA.AccountType=0 THEN UB.Vyhzh ELSE PB.Vyhzh END vyhzhByAdvance");//银行账户编码

        //明细1
        cond.addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceByRecharge FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode ='YZZHLX000' GROUP BY Pid) D1 on D1.Pid = A.AdvanceAccountId AND 1=1")
                .addField("ISNULL(D1.totalPriceByRecharge, 0) AS totalPriceByRecharge")//账户备用金额,字段“总额”之和（预支类型为充值）


                .addLeftJoin("TS_UserChange QWE ON QWE.Id = A.CreateChangeId")
                .addField("(QWE.UserId + '/' + QWE.UserName) AS _ys_nameLinked")//制单人

                .addLeftJoin("TS_UserInfo CU ON CU.UserId = QWE.UserId")//用户信息表
                .addLeftJoin("TS_OrganizationInfo UO ON UO.Id = CU.OrgId")//用户所属机构
                .addField("QWE.UserId AS userld")
                .addField("CU.OrgId AS orgId");


        //排序
        cond.setOrderby("A.Bid DESC");
        cond = commonApiService.dataAuth(MenuId.TCW_AdvanceAccountRecharge, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tcwAdvanceAccountRecharge:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwAdvanceAccountRecharge cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            /*
            String vyhzhmc = ConditionUtil.getConditionValue(conditions, "_ys_vyhzhmc");//银行账户名称
            if (vyhzhmc != null){
                cond.where("U.Vyhzhmc LIKE '%" + vyhzhmc + "%'" + " OR  P.Vyhzhmc LIKE '%" + vyhzhmc + "%'");
            }

             */
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwAdvanceAccountRecharge cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_AdvanceAccountRecharge)
                    .where("A.Code != 'ope'")
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<TcwAdvanceAccountRecharge> util = new ExportExcelUtils<>(new TcwAdvanceAccountRecharge());
            String toFilePath = util.exportExcel(listData, listField, "预支账户充值单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwAdvanceAccountRechargeService.add(params,MenuId.TCW_AdvanceAccountRecharge);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 编辑
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwAdvanceAccountRechargeService.update(params,MenuId.TCW_AdvanceAccountRecharge);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 流转通过
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcwAdvanceAccountRechargeService.flowPass(id, ShiroUtils.getUserId());
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("印章申请表流转出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        TcwAdvanceAccountRecharge entity = new TcwAdvanceAccountRecharge().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowRefuse(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("员工入职申请表转驳回出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){

        TcwAdvanceAccountRecharge entity = new TcwAdvanceAccountRecharge().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowInit(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("员工入职申请表转驳回出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 删除
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/delete")
    @ResponseBody
    public R del(HttpServletRequest request, Long id){
        try {
            return tcwAdvanceAccountRechargeService.del(id);
        } catch (Exception e) {
            logger.error("删除员工入职申请表出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 归还单调用查询
     */
    @RequestMapping("/searchGh")
    @ResponseBody
    public LayuiTableVoJA searchGh(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwAdvanceAccountRecharge cond
    ){
        try {
            cond = setSeachSql(cond);
            //查询已经被使用的
            cond.where("(SELECT count(1) FROM TCW_AdvanceAccountBack WHERE AdvanceAccountRechargeId = A.Id) = 0" );
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 打印
     */
    @RequestMapping("/exportdy")
    @ResponseBody
    public R exportdy(HttpServletRequest request,@RequestParam Map<String, Object> params) throws Exception{
        String bid = params.get("bid").toString();
        List<Map<String,Object>> infoList = new TcwAdvanceAccountRecharge()
                .addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
                .addField("U.DeptName AS deptName")//制单人部门
                .addField("FORMAT(A.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByStr")//创建时间

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS auditingTime")//审核时间



                .addLeftJoin("THR_OperateCompanyApply C ON C.Vgsbm = A.Vgsbm ")
                .addField("C.Vgsjc AS vgsjc")//运营公司简称

                .addLeftJoin("TB_CompanyInfo CI ON CI.Vid = A.CompanyVid ")
                .addField("CI.Vname AS vname")//所属公司

                .addLeftJoin("TB_CompanyBankInfo CB ON CB.Id = A.CompanyBankInfoId ")
                .addField("CB.Vyhzhmc AS vyhzhmc")//付款账户名称
                .addField("CB.Vyhzh AS vyhzh")//付款账号
                .addField("CB.Vkhh AS vkhh")//付款开户行

                .addLeftJoin("TCW_AdvanceAccount AA ON AA.Id = A.AdvanceAccountId ")
                .addField("AA.Code AS code")//预支账户编码
                .addField("AA.Name AS name")//付款账户名称


                //.addLeftJoin("TS_UserBankInfo UB ON AA.UserBankInfoId = UB.Id")
                .addLeftJoin("TS_UserInfo B on  B.UserId = AA.UserId")
                .addLeftJoin("TS_OrganizationInfo O on  O.Orgid = AA.Orgid")
                .addField("O.DeptName AS deptName")//账户管理部门
                .addField("B.RoleName AS roleName")//负责人岗位
                .addField("(B.UserId + '/' + B.UserName) AS nameLinked")//账户管理负责人

                .addLeftJoin("TS_UserBankInfo UB ON AA.UserBankInfoId = UB.Id AND AA.AccountType=0")
                .addLeftJoin("TCW_PartnerBankInfo PB ON AA.PartnerBankInfoId = PB.Id AND AA.AccountType=1")
                //.addField("CASE WHEN AA.AccountType=0 THEN U.Vyhzhmc ELSE P.Vyhzhmc END _ys_vyhzhmc")//银行账户名称
                //.addField("CASE WHEN AA.AccountType=0 THEN U.Vkhh ELSE P.Vkhh END _ys_vkhh")//开户行
                //.addField("CASE WHEN AA.AccountType=0 THEN U.Vyhzh ELSE P.Vyhzh END _ys_vyhzh")//银行账户编码

                .addField("CASE WHEN AA.AccountType=0 THEN UB.Vyhzhmc ELSE PB.Vyhzhmc END vyhzhmcByAdvance")//银行账户名称
                .addField("CASE WHEN AA.AccountType=0 THEN UB.Vkhh ELSE PB.Vkhh END vkhhByAdvance")//开户行
                .addField("CASE WHEN AA.AccountType=0 THEN UB.Vyhzh ELSE PB.Vyhzh END vyhzhByAdvance")//银行账户编码

                //明细1
                .addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceByRecharge FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode ='YZZHLX000' GROUP BY Pid) D1 on D1.Pid = A.AdvanceAccountId AND 1=1")
                .addField("ISNULL(D1.totalPriceByRecharge, 0) AS totalPriceByRecharge")//账户备用金额,字段“总额”之和（预支类型为充值）


                .addLeftJoin("TS_UserChange QWE ON QWE.Id = A.CreateChangeId")
                .addField("(QWE.UserId + '/' + QWE.UserName) AS _ys_nameLinked")//制单人

                .addLeftJoin("TS_UserInfo CU ON CU.UserId = QWE.UserId")//用户信息表
                .addLeftJoin("TS_OrganizationInfo UO ON UO.Id = CU.OrgId")//用户所属机构
                .addField("QWE.UserId AS userld")
                .addField("CU.OrgId AS orgId")
                .addField("A.RechargePrice AS rechargePrice")
                .setBid(bid)
                .queryMap();


        if(infoList!=null && infoList.size()>0){
            Map<String,Object> sonByOne = infoList.get(0);

            BigDecimal sonAmountTotal = BigDecimal.ZERO;
            for (Map<String, Object> son : infoList){
                sonAmountTotal = sonAmountTotal.add(new BigDecimal(son.get("rechargePrice").toString()));
            }

            String nameStr =  (sonByOne.get("vyhzhmcByAdvance")!=null ? sonByOne.get("vyhzhmcByAdvance").toString():"")
                    + "/" + (sonByOne.get("vyhzhByAdvance")!=null ? sonByOne.get("vyhzhByAdvance").toString():"")
                    + "/" + (sonByOne.get("vkhhByAdvance")!=null ? sonByOne.get("vkhhByAdvance").toString():"");

            List<NameValueDto> listData = new ArrayList<>();
            listData.add(new NameValueDto("单据编号",bid));
            listData.add(new NameValueDto("申请人",sonByOne.get("_ys_createUserName").toString()));
            listData.add(new NameValueDto("申请部门",sonByOne.get("deptName").toString()));
            listData.add(new NameValueDto("收款账号",nameStr));
            listData.add(new NameValueDto("付款金额",sonAmountTotal.toString()));
            listData.add(new NameValueDto("付款说明",sonByOne.get("remark").toString()));
            String url = pdfService.generatePDF(bid,"预支账户充值", sonByOne.get("vname").toString(), sonByOne.get("createTimeByStr").toString(),listData);
            return R.ok(url);
        }else {
            return R.error("未查询到要导出的数据");
        }


    }
}